'''
@author: Aurelien Deharbe


This file is part of Cute-Server.

Cute-Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Cute-Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Cute-Server.  If not, see <http://www.gnu.org/licenses/>.
'''

from PySide.QtCore import QThread, Signal
import socket
import re
import json

class CClientThread(QThread):
    
    command = Signal(str, QThread)
    script = Signal(str, str, QThread)
    killme = Signal(QThread)
    uuidno = 1
    scriptstart = re.compile(r'#scriptstart\((.+),([0-9]+)\)#')
    
    def __init__(self, host, port, mutex):
        QThread.__init__(self)
        self._host = host
        self._port = port
        self._mutex = mutex
        self._uuid = "client" + str(self.uuidno)
        CClientThread.uuidno = CClientThread.uuidno + 1
    
    def run(self):
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.connect((self._host, self._port))
        scripting = 0
        while True:
            cmd = self._sock.recv(256).rstrip()
            if not cmd:
                break
            m = CClientThread.scriptstart.match(cmd)
            self._mutex.lock()
            if m:
                scripting = 1
                scriptname = m.group(1)
                script = "def " + m.group(1) + "(self,"
                args = []
                for i in range(1, int(m.group(2))+1):
                    args.append(str(i))
                if int(m.group(2)):
                    script = script + "arg" + ",arg".join(args)
                script = script + "):\n"
                self._sock.send(json.dumps(["ok"]))
                self._mutex.unlock()
            elif cmd == "#scriptend#":
                self.script.emit(script, scriptname, self)
                scripting = 0
            else:
                if scripting:
                    script = script + cmd + "\n"
                    self._sock.send(json.dumps(["ok"]))
                    self._mutex.unlock()
                else:
                    self.command.emit(cmd, self)
        
        # client disconnected
        self.killme.emit(self)
    
    def cmdret(self, res):
        self._mutex.unlock()
        self._sock.send(res + "\n")
    
    def slotret(self, res):
        self._mutex.lock()
        self._sock.send(res + "\n")
        self._mutex.unlock()
    
    def getUuid(self):
        return self._uuid



if __name__ == '__main__':
    print "Please use the cuteserver script to run it"
